<template>
	<view>
		<view class="bagW">
			<view class="pdr10 pdl10">
				<view class="d-flex align-center justify-between">
					<view>
						<text class="defaultColor">{{ reqiure ? '*' : ' '}}</text>
						<text class="mgl5 fs16 text-black">{{title}}</text>
					</view>
					<view>
						<text class="text-black fs16">{{content ? content.length : 0}}/</text><text class="text-7f fs12">{{maxlength}}</text>
					</view>
				</view>
			</view>
			<view v-if="needEx">
				<view  class="toolbar pdr5 pdl5 d-flex align-center flex-wrap">
					<i class="iconfont icon-zitijiacu" :class="[formats.bold ? 'ql-active' : '']" @click="format($event,{name:'bold',value:true})"></i>
					<i class="iconfont icon-zitixieti " :class="[formats.italic ? 'ql-active' : '']" @click="format($event,{name:'italic',value:true})"></i>
					<i class="iconfont icon-zitixiahuaxian " :class="[formats.underline ? 'ql-active' : '']" @click="format($event,{name:'underline',value:true})"></i>
					<i class="iconfont icon-zitishanchuxian " :class="[formats.strike ? 'ql-active' : '']" @click="format($event,{name:'strike',value:true})"></i>
					<i class="iconfont icon-zuoduiqi" :class="[formats.align === 'left' ? 'ql-active' : '']" @click="format($event,{name:'align',value:'left'})"></i>
					<i class="iconfont icon-juzhongduiqi" :class="[formats.align === 'center' ? 'ql-active' : '']" @click="format($event,{name:'align',value:'center'})" data-name="align" data-value="center"></i>
					<i class="iconfont icon-youduiqi" :class="[formats.align === 'right' ? 'ql-active' : '']" @click="format($event,{name:'align',value:'right'})" data-name="align" data-value="right"></i>
					<i class="iconfont icon-zuoyouduiqi" :class="[formats.align === 'justify' ? 'ql-active' : '']" @click="format($event,{name:'align',value:'justify'})" data-name="align" data-value="justify"></i>
					<i class="iconfont icon-line-height" :class="[formats.lineHeight ? 'ql-active' : '']" @click="format($event,{name:'lineHeight',value:'2'})" data-name="lineHeight" data-value="2"></i>
					<i class="iconfont icon-Character-Spacing" :class="[formats.letterSpacing ? 'ql-active' : '']" @click="format($event,{name:'letterSpacing',value:'2em'})" data-name="letterSpacing" data-value="2em"></i>
					<i class="iconfont icon-722bianjiqi_duanqianju" :class="[formats.marginTop ? 'ql-active' : '']" @click="format($event,{name:'marginTop',value:'20px'})" data-name="marginTop" data-value="20px"></i>
					<i class="iconfont icon-723bianjiqi_duanhouju " :class="[formats.marginBottom ? 'ql-active' : '']" @click="format($event,{name:'marginBottom',value:'20px'})" data-name="marginBottom" data-value="20px"></i>
					<i class="iconfont icon-clearedformat" @tap="removeFormat"></i>
					<i class="iconfont icon-font" :class="[formats.fontFamily ? 'ql-active' : '']" @click="format($event,{name:'fontFamily',value:'Pacifico'})" data-name="fontFamily" data-value="Pacifico"></i>
					<i class="iconfont icon-fontsize " :class="[formats.fontSize === '24px' ? 'ql-active' : '']" @click="format($event,{name:'fontSize',value:'24px'})" data-name="fontSize" data-value="24px"></i>
					<i class="iconfont icon-text_color " :class="[formats.color === '#0000ff' ? 'ql-active' : '']" @click="format($event,{name:'color',value:'#0000ff'})" data-name="color" data-value="#0000ff"></i>
					<i class="iconfont icon-fontbgcolor " :class="[formats.backgroundColor === '#00ff00' ? 'ql-active' : '']" @click="format($event,{name:'backgroundColor',value:'#00ff00'})" data-name="backgroundColor" data-value="#00ff00"></i>
					<i class="iconfont icon-date" @tap="insertDate"></i>
					<i class="iconfont icon--checklist" @click="format($event,{name:'list',value:'check'})" data-name="list" data-value="check"></i>
					<i class="iconfont icon-youxupailie" :class="[formats.list === 'ordered' ? 'ql-active' : '']" @click="format($event,{name:'list',value:'ordered'})"  data-name="list" data-value="ordered"></i>
					<i class="iconfont icon-wuxupailie" :class="[formats.list === 'bullet' ? 'ql-active' : '']" @click="format($event,{name:'list',value:'bullet'})" data-name="list" data-value="bullet"></i>
					<i class="iconfont icon-undo" @tap="undo"></i>
					<i class="iconfont icon-redo" @tap="redo"></i>
					<i class="iconfont icon-outdent" :class="[formats.indent === '-1' ? 'ql-active' : '']" @click="format($event,{name:'indent',value:'-1'})" data-name="indent" data-value="-1"></i>
					<i class="iconfont icon-indent" :class="[formats.indent === '+1' ? 'ql-active' : '']" @click="format($event,{name:'indent',value:'+1'})" data-name="indent" data-value="+1"></i>
					<i class="iconfont icon-fengexian" @tap="insertDivider"></i>
					<i class="iconfont icon-charutupian" @tap="insertImage"></i>
					<i class="iconfont icon-format-header-1 " :class="[formats.header === 1 ? 'ql-active' : '']" @click="format($event,{name:'header',value:1})" data-name="header" :data-value="1"></i>
					<i class="iconfont icon-format-header-2 " :class="[formats.header === 2 ? 'ql-active' : '']" @click="format($event,{name:'header',value:2})" data-name="header" :data-value="2"></i>
					<i class="iconfont icon-format-header-3 " :class="[formats.header === 3 ? 'ql-active' : '']" @click="format($event,{name:'header',value:3})" data-name="header" :data-value="3"></i>
					<i class="iconfont icon-format-header-4 " :class="[formats.header === 4 ? 'ql-active' : '']" @click="format($event,{name:'header',value:4})" data-name="header" :data-value="4"></i>
					<i class="iconfont icon-zitixiabiao " :class="[formats.script === 'sub' ? 'ql-active' : '']" @click="format($event,{name:'script',value:'sub'})" data-name="script" data-value="sub"></i>
					<i class="iconfont icon-zitishangbiao" :class="[formats.script === 'super' ? 'ql-active' : '']" @click="format($event,{name:'script',value:'left'})" data-name="script" data-value="super"></i>
					<!-- <i class="iconfont icon-quanping"></i> -->
					<i class="iconfont icon-shanchu" @tap="clear"></i>
					<i class="iconfont icon-direction-rtl " :class="[formats.direction === 'rtl' ? 'ql-active' : '']" @click="format($event,{name:'direction',value:'rtl'})" data-name="direction" data-value="rtl"></i>
				</view>
			</view>
			<view class="pl-10  pdl10 pdr10" :style="editorStyle">
				<editor id="editor" class="border-radius-5 border pd5" :class="editorStyle ? 'ql-container': ''"
						show-img-size show-img-resize
						:read-only="readOnly"
						@ready="onEditorReady"
						@statuschange="onStatusChange"
						@input="onContentChange"
						@blur="onNoFocus"
				></editor>
			</view>
		</view>
		<!-- <button @click="clickLogText">打印结果</button> -->

	</view>
</template>

<script>
	export default {
		name:'EditorComp',
		props:{
			title:{
				type:String,
				default:"内容"
			},
			//字符最大长度
			maxlength:{
				type:[String, Number],
				default:'100'
			},
			// 必填
			reqiure:{
				type:Boolean,
				default:false,
			},
			//报错
			fail:{
				type:Boolean,
				default:false,
			},
			needEx:{//操作
				type:Boolean,
				default:true,
			},
			editorStyle:{
				type:String,
				default:"",
			},
			initContext:{//初始值
				default:null,
			},
			readOnly:{//只读
				type:Boolean,
				default:false,
			},
		},
		data() {
			return {
				content: '',
				formats: {}
			}
		},
		watch:{
			initContext(value){
				// console.log("initContext",value)
				if(value){
					this.onEditorReady();
				}
			}
		},
		onLoad() {
			// console.log("initContext")
		},
		methods: {
			onEditorReady() {
				this.createSelectorQuery().select('#editor').context((res) => {
					// console.log('cccc', res,this.initContext)
					this.editorCtx = res.context;// h5不支持 context
					// if (wx.getStorageSync("content")) { // 设置~历史值
					//   this.editorCtx.insertText(wx.getStorageSync("content")) // 注意：插入的是对象
					// }
					if(this.initContext){
						this.editorCtx.setContents({//赋值
							html:this.initContext
						})
					}
				}).exec()
			},
			// 返回选区已设置的样式
			onStatusChange(e) {
				console.log(e.detail);
				const formats = e.detail;
				this.formats = formats
			},
			// 失去焦点
			onNoFocus(e) {
				// console.log("失去焦点")
				// console.log(e.detail)
				this.clickLogText();
			},
			onContentChange(e){
				this.clickLogText();
			},
			// 获取内容
			clickLogText(e) {
				this.editorCtx.getContents({
					success: (res)=>{
						// console.log("html>>>>",res.html);
						this.$emit('change',{
							content:res.html,
							res:res,
						})
						// wx.setStorageSync("content", res.html); // 缓存本地
					}
				})
			},
			format(e,values) {
				let {
					name,
					value
				} = values;
				if (!name) return;
				this.editorCtx.format(name, value);
			},
			insertImage() {
				const $this = this;
				wx.chooseImage({
					count:1,
					success:(res)=>{
						if(this.hepler && this.hepler.weappUploadFile){
							this.hepler.weappUploadFile(res.tempFilePaths[0]).then((rsp)=>{

								if(rsp&&rsp.data){
									try{
										let res = JSON.parse(rsp.data)
										console.log('res.data',res.data)
										if(200 == res.status){
											$this.editorCtx.insertImage({
												src:res.data.path,
												width:'100%',
												success:()=>{
													console.log("insert image success")
												}
											})
										}
									}catch(e){
										//TODO handle the exception
										console.error('upload pic return data error!!!');
									}
								}
							})
						}


						// wx.uploadFile({
						// 	url:'服务器地址',
						// 	filePath:res.tempFilePaths[0],
						// 	name:'file',
						// 	success:(res)=>{
						// 		console.log("图片上传后返回数据",res.data);
						// 		let data = JSON.parse(res.data);
						// 		console.log("url>>>",data.data.url)
						// $this.editorCtx.insertImage({
						// 	src:"https://jdw.easydemo.me/front/doc/file?filePath=/static/18575960340/documents/2020/4/7/1130817a90a8.jpg",
						// 	success:()=>{
						// 		console.log("insert image success")
						// 	}
						// })
						// 	}
						// })
					}
				})
			},
			// 插入分割线
			insertDivider() {
				this.editorCtx.insertDivider({
					success: function() {
						// console.log('insert divider success')
					}
				});
			},
			// 清除
			clear() {
				this.editorCtx.clear({
					success: function(res) {
						// console.log("clear success")
					}
				});
			},
			// 移除样式
			removeFormat() {
				this.editorCtx.removeFormat();
			},
			// 插入当前日期
			insertDate() {
				const date = new Date()
				const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
				this.editorCtx.insertText({
					text: formatDate
				});
			},
			//撤销
			undo() {
				// console.log("undo",this.editorCtx)
				this.editorCtx.undo();
			},
			//恢复
			redo() {
				// console.log("redo",this.editorCtx)
				this.editorCtx.redo();
			},
		},
	}
</script>

<style lang="scss" scoped>
	@import "../common/icon-font/editorIconfont.css";
	@import "../common/common.scss";
	.ql-container{
		height:100%;
		min-height:40upx;
	}
	.ql-active {
		color: #06c;
	}

	.icon-charutupian:before {
		content: "\ec82";
	}

	.toolbar {
		box-sizing: border-box;
		padding: 0 20upx;
		border-bottom: 0;
		font-family: "Helvetica Neue", "Helvetica", "Arial", sans-serif;
		margin-bottom: 10rpx;
		i {
			padding:15upx;
		}
	}
</style>
